package cn.com.zhbs.netty.springListener;

import cn.com.zhbs.netty.EchoServer;
import cn.com.zhbs.netty.utils.SysConfig;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class StartNettyListener implements ApplicationListener<ContextRefreshedEvent>
{
    private final static int autoStart = Integer.parseInt(SysConfig.getInstance().getProperty("autoStart"));

    // 在Spring容器被加载后执行以下内容
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event)
    {
        if(event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext"))
        {
            if(autoStart==1){
                // 创建线程池。（这里理论上可以同时开启多个netty，这取决于你的线程池容量）
                ExecutorService executor = Executors.newFixedThreadPool(1);

                // 提交任务到线程池中执行。
                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        EchoServer.start();
                    }
                });
            }
        }

    }

}